<!--报价单送审核MSTP-->
<template>
  <div class="generate-quotation-box ne-relative"
       v-loading="loading"
       element-loading-customClass="ne-loading"
       element-loading-background="rgba(255, 255, 255, 0.6)"
  >
    <div class="" style="height: 100%;overflow-y: auto;">
      <el-form
          ref="TcForm2"
          label-position="left"
          label-width="1rem"
          :model="Form"
      >
        <el-row>
          <tc-form2 :form="Form"></tc-form2>
          <h2 class="ne-title-v2">一次性费用详单</h2>
          <DicTable
              height="100%"
              ref="GQTable"
              border
              header-row-class-name="header-row-class"
              :merge-cells="mergeCells"
              :columnData="GQtbs.tableColumns"
              :tableData="GQtbs.tableData"
              :loading="GQtbs.tableLoading"
              :pager="false"
          >
            <template #comments="{ row }">
              <div v-if="row.hasOwnProperty('comments')">
                <el-input type="textarea" v-model="row.comments"></el-input>
              </div>
            </template>
          </DicTable>
          <tc-form2 class="mar-20" :form="FormB"></tc-form2>
        </el-row>
      </el-form>
      <el-row class="fixed">
        <el-col :span="24" class="flex flex-center">
          <div v-if="showBtn2" style="margin-right: .1rem">
          <el-button type="primary" size="medium" @click="saveAudit">确定</el-button>
          <el-button type="primary" size="medium">返回</el-button>
         </div>
          <div v-if="showBtn1" style="margin-right: .1rem">
          <el-button type="primary" @click="reSave" size="medium">重新报价</el-button>
          <el-button type="primary" size="medium" @click="AuditdialogVisible=true">送审核</el-button>
          </div>
          <el-button v-if="showBtn1||showBtn2" type="primary" @click="save" size="medium">保存</el-button>
          <el-button type="primary" size="medium" @click="exportExcel">输出Excel</el-button>
          <el-button size="medium" @click="closeFun">关闭</el-button>
        </el-col>
      </el-row>
    </div>
    <!-- Form -->
    <el-dialog append-to-body :close-on-click-modal='false' title="送审核报价单" v-if="AuditdialogVisible" :visible.sync="AuditdialogVisible">
      <div class="flex-column" style="width: 100%"
          v-loading="loading2"
          element-loading-customClass="ne-loading"
          element-loading-background="rgba(255, 255, 255, 0.6)"
      >
        <el-form :model="audName">
          <el-form-item :label="audName.cName" label-width="1rem">
            <el-select v-model="audName.cValue" placeholder="请选择">
              <el-option
                  v-for="(item,index) in audName.opt"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer text-center">
          <el-button type="primary" @click="sendAuditSave">发送</el-button>
          <el-button @click="AuditdialogVisible = false">取 消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import TcForm2 from '@/components/public/TcForm2';
import DicTable from '@/components/public/DicTable';
import CustOrderService from '@/api/order/CustOrderService';
import {mapState} from 'vuex';
import refreshList from '@/mixins/custorder/refreshList';
import OrderService from "@/api/order/OrderService.js";

export default {
  name: 'GenerateQuotations',
  mixins: [refreshList],
  data() {
    return {
      loading: false,
      loading2: false,
      mergeCells: [],
      AuditdialogVisible: false,
      Form: {
        'custSoNumber': {
          type: 'Ipt',
          name: '流水号',
          readonly: true,
          value: '',
          id: 'custSoNumber',
          show: true,
          span: 6,
        },
        'custName': {
          type: 'Ipt',
          name: '客户名称',
          readonly: true,
          value: '',
          id: 'custName',
          show: true,
          span: 6,
        },
        'contactCd': {
          type: 'Ipt',
          name: '合同编码',
          readonly: true,
          value: '',
          id: 'contactCd',
          show: true,
          span: 6,
          marginRight: '25%',
        },
        'custNumber': {
          type: 'Ipt',
          name: '客户编码',
          readonly: true,
          value: '',
          id: 'custNumber',
          show: true,
          span: 6,
        },
        'payType': {
          type: 'Ipt',
          name: '收费方式',
          readonly: true,
          value: '',
          id: 'payType',
          show: true,
          span: 6,
          marginRight: '50%',
        },
        'allRmb': {
          type: 'Ipt',
          name: '合计',
          readonly: true,
          value: '',
          id: 'priceRmb',
          show: true,
          span: 6,
        },
        'rmbBig': {
          type: 'Ipt',
          name: '大写(元)',
          readonly: true,
          value: '',
          id: 'rmbBig',
          show: true,
          span: 6,
        },
        'rmbSmall': {
          type: 'Ipt',
          name: '小计',
          readonly: true,
          value: '',
          id: 'priceRmb',
          show: true,
          span: 6,
          marginRight: '25%',
        },
      },
      FormB: {
        'rmbxj': {
          type: 'Ipt',
          name: '人民币小计',
          readonly: true,
          value: '',
          id: 'priceRmb',
          show: true,
          span: 6,
          marginRight: '75%',
        },
        'moneySum': {
          type: 'Ipt',
          name: '合计',
          readonly: true,
          value: '',
          id: 'priceRmb',
          show: true,
          span: 6,
          marginRight: '75%',
        },
        'orderComment': {
          type: 'textarea',
          name: '备注',
          readonly: false,
          value: '',
          id: 'orderComment',
          show: true,
          span: 12,
          marginRight: '50%',
        },
      },
      audName: {
        type: 'select',
        cName: '审核人',
        cValue: '',
        required: true,
        opt: [],
        show: true,
        span: 24,
      },
      GQtbs: {
        tableColumns: [
          {field: 'circuitName', title: '电路名称', width: '4%'},
          {field: 'inputMode', title: '接入电路类型', width: '6%'},
          {field: 'nodeName', title: '单位'},
          {field: 'productName', title: '业务种类'},
          {field: 'custOrderType', title: '类型'},
          {field: 'speedLink', title: '速率'},
          {field: 'moneyRmbMat', title: '工料费'},
          {field: 'moneyRmbTest', title: '调测费'},
          {field: 'moneyRmbPro', title: '手续费'},
          {field: 'subtotal', title: '小计'},
          {field: 'moneyRmbEng', title: '工程费'},
          {field: 'moneyRmbDev', title: '设备费用'},
          {field: 'receivables', title: '应收款'},
          {field: 'equipmentName', title: '设备名称'},
          {field: 'resSum', title: '资源情况', width: '15%'},
          {slotName: 'comments', title: '备注', width: '7%'},
        ],
        tableData: [],
        tableLoading: false,
      },
      showBtn1: false,
      showBtn2: false,
      taskId: null,
    };
  },
  props: {
    ODKInfo: {
      type: Object,
    },
    CTOInfo: {
      type: Object,
    },
  },
  mounted() {
  },
  computed: {
    ...mapState('user', ['user']),
  },
  created() {
    // // 临时
    // let params = {
    //   custId: "181",
    //   custOrderId: "11406",
    //   custSoNumber: "JT202100007492",
    //   prodType: "dkyw",
    //   offerId: "10010021"
    // };
    // Object.assign(this.CTOInfo,params);
    this.getAudUserList();
    this.getDetail();
  },
  components: {TcForm2, DicTable},
  methods: {
    exportExcel(){
      // http://localhost:8085/order-query/outputNoticeExcel?templateType=2006&custId=203&custOrderId=14848&acctItemListId=4129&userId=1
        this.outputNoticeExcel("2005","报价单");
    },
    async outputNoticeExcel(type, xsName) {

      //  let params = {
      //               interFaceType: "ORDER",
      //               sqlId: "2021082404",
      //               paramStr:"orderSoNbr:"+this.CTOInfo.custSoNumber
      //           };
              // console.log("param",params);
              // let result = await OrderService.executeSql(params);
              // console.log("result",result);


      let param = {
        custOrderId: this.CTOInfo.custOrderId,
        offerType: this.CTOInfo.offerType,
        orderItemIds:"",
        userId: this.user.staffId + "",
        custId: this.CTOInfo.custId,
        templateType: type,
      };

     
     console.log("this.CTOInfo",this.CTOInfo);
     console.log("outputNoticeExcel",param);
      const res = await CustOrderService.outputNoticeExcel(param);
      const blob = new Blob([res]);
      let fileName = xsName + ".xls";
      if ("download" in document.createElement("a")) {
        const elink = document.createElement("a");
        elink.download = fileName;
        elink.style.display = "none";
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        URL.revokeObjectURL(elink.href);
        document.body.removeChild(elink);
      } else {
        navigator.msSaveBlob(blob, fileName);
      }
    },
    btnInit(res) {
      // 临时
      let {audFlag, createBy, custManagerId, sendAudFlag} = res,
          userId = this.user.staffId,
          taskId = this.taskId;
          //默认都隐藏 否则客户点击完按钮再次刷新 还会展示
          this.showBtn1 = false;
          this.showBtn2 = false;                    
      if (createBy == userId) {
        if (taskId != null && taskId.indexOf('TACHE00060002') != -1 &&
            (audFlag !== '1' || (sendAudFlag == 1 && audFlag == 2))) {
          // 展示 送审核 ，重新报价 ，保存
          this.showBtn1 = true;
        }
      }
      if (custManagerId == userId) {
        if (taskId != null && taskId.indexOf('TACHE00060003') != -1 && sendAudFlag == '1' && audFlag != '1') {
          // 展示 确认 ，保存
          this.showBtn2 = true;
        }
      }
    },
    async saveAudit() {
      this.loading = true;
      let {custOrderId, custSoNumber, offerType, prodOfferId, custId, orderAuditId} = this.CTOInfo;
      let comment = this.FormB.orderComment.value,
          oneOrmany = 'many',
          prodType = offerType,
          taskId = this.taskId,
          userId = this.user.staffId,
          orderAudFlag = 1;
      const result = await CustOrderService.saveAuditGenerateQuotation({
        orderAuditId,
        taskId,
        orderAudFlag,
        userId,
        oneOrmany,
        custOrderId,
        custSoNumber,
        prodType,
        prodOfferId,
        custId,
        comment,
      });
      this.loading = false;
      if (result.meta.resultCode == 0) {
        this.$message({
          type: 'success',
          message: '保存成功!',
        });
        this.getDetail();
        this.eventDoSearch();
      } else {
        this.$message({
          showClose: true,
          message: result.meta.resultMsg,
          type: 'error',
        });
      }
    },
    async getDetail() {
      this.loading = true;
      let {custOrderId, custSoNumber, offerType, prodOfferId, custId} = this.CTOInfo,
          params = {custOrderId, custSoNumber, custId, ...{prodType: offerType, offerId: prodOfferId}};
      const result = await CustOrderService.qryGenerateQuotationDetail(params),
          res = result.meta;
      this.loading = false;
      if (res.resultCode == '0') {
        if (res.orderBandwidthQuoteLowers) {
          this.GQtbs.tableData = this.tableDataInit(res.orderBandwidthQuoteLowers);
          // this.mergeCellInit(this.GQtbs.tableData);
        }
        if (res.orderBandwidthQuoteUppers && res.orderBandwidthQuoteUppers.length > 0) {
          for (var key in res.orderBandwidthQuoteUppers[0]) {
            let value = res.orderBandwidthQuoteUppers[0][key];
            for (var key2 in this.Form) {
              if (this.Form[key2].id == key) {
                this.Form[key2].value = value;
              }
            }
            for (var key2 in this.FormB) {
              if (this.FormB[key2].id == key) {
                this.FormB[key2].value = value;
              }
            }
          }

          if (res.orderBandwidthQuoteUppers[0].hasOwnProperty('priceRmb')) {
            const result2 = await CustOrderService.transferAmount({amount: res.orderBandwidthQuoteUppers[0].priceRmb});
            this.Form.rmbBig.value = result2.meta.amount;
          }
        }
        if (res.taskIds) {
          for (var key in res.taskIds) {
            this.taskId = res.taskIds[key].taskId;
          }
        }
        this.btnInit(res);
      } else {
        this.$message({
          showClose: true,
          message: res.resultMsg,
          type: 'error',
        });
      }
    },
    async getAudUserList() {
      let {custId, custOrderId} = this.CTOInfo;
      const result = await CustOrderService.gryQuotationAudUserList({custId, custOrderId});
      this.audName.opt = {...result.meta};
    },
    async sendAuditSave() {
      this.loading2 = true;
      let {custOrderId, custSoNumber, offerType, orderAuditId, custId} = this.CTOInfo;
      let audUserId = this.audName.cValue,
          audUserName = this.getLabel(this.audName.opt, audUserId),
          oneOrmany = 'many',
          taskId = this.taskId,
          prodType = offerType,
          userId = this.user.staffId;
      const result = await CustOrderService.sendAuditGenerateQuotation({
        taskId,
        oneOrmany,
        userId,
        custOrderId,
        custSoNumber,
        prodType,
        orderAuditId,
        custId,
        audUserId,
        audUserName,
      });
      this.loading2 = false;
      if (result.meta.resultCode == 0) {
        this.$message({
          type: 'success',
          message: '保存成功!',
        });
        this.AuditdialogVisible = false;
        this.eventDoSearch();
        this.getDetail();
      } else {
        this.$message({
          showClose: true,
          message: result.meta.resultMsg,
          type: 'error',
        });
      }
    },
    async save() {
      this.loading = true;
      let {custOrderId, custSoNumber, orderAuditId, custId} = this.CTOInfo;
      // 再详情返回表格中取
      let orderItems = [];
      this.GQtbs.tableData.forEach((item,index)=>{
        if(index==0||item.mainOrderItemId!=this.GQtbs.tableData[index-1].mainOrderItemId){
          orderItems.push({
            custId: custId,
            actType: "MOD",
            remark: item.comments,
            orderItemId: item.mainOrderItemId
          })
        }
      });
      let params = {
        custId: custId,
        custSoNumber: custSoNumber,
        userId: this.user.staffId,
        orgId: this.user.orgId,
        userName: this.user.staffName,
        orderAuditId: orderAuditId,
        orderItems: orderItems,
        customerOrders: [{
          custId: custId,
          actType: "MOD",
          remark: this.FormB.orderComment.value,
          custOrderId: custOrderId
        }],
      }
      
      const result = await CustOrderService.commonOrderUpdate(params);
      this.loading = false;
      if (result.meta.resultCode == 0) {
        this.$message({
          type: 'success',
          message: '保存成功!',
        });
        this.eventDoSearch();
        this.getDetail();
      } else {
        this.$message({
          showClose: true,
          message: result.meta.resultMsg,
          type: 'error',
        });
      }
    },
    //重新报价 
    async reSave() {
      this.loading = true;
      let {custOrderId, custSoNumber, offerType, orderAuditId, custId} = this.CTOInfo;
      let oneOrmany = 'many',
          taskId = this.taskId,
          prodType = offerType,
          newQuoteFlag = "1", //重新报价 标识  
          userId = this.user.staffId;
          
      const result = await CustOrderService.reSaveGenerateQuotation({
        taskId,
        oneOrmany,
        userId,
        custOrderId,
        custSoNumber,
        prodType,
        orderAuditId,
        newQuoteFlag,
        custId,
      });
      this.loading = false;
      if (result.meta.resultCode == 0) {
        this.$message({
          type: 'success',
          message: '重新报价完成',
        });
        this.eventDoSearch();
        this.getDetail();
      } else {
        this.$message({
          showClose: true,
          message: result.meta.resultMsg,
          type: 'error',
        });
      }
    },
    closeFun() {
      this.$emit('update:show', false);
    },
    mergeCellInit(arr) {
      let len = arr.length;
      this.mergeCells = [];
      for(var i = 0;i<len;i++){
        if(i%2 == 0){
          this.mergeCells.push(
            {row: i, col: 0, rowspan: 2, colspan: 1},
            {row: i, col: 15, rowspan: 2, colspan: 1},
          );
        }
      }
    },
    tableDataInit(arr) {
      arr.sort(function(a,b){
        return a.mainOrderItemId - b.mainOrderItemId
      });
      let le = {moneyRmbMat: '0', moneyRmbTest: '0', moneyRmbPro: '0', moneyRmbEng: '0', moneyRmbDev: '0'};
      let newarr = [];
      arr.map((item, index) => {
        let les = {...le};
        Object.assign(les, item);
        item = {...les};
        if (!item.comments) {
          item.comments = '';
        }
        if(!item.nodeName){
          item.nodeName = ''
        }
        if(index>0 && item.mainOrderItemId==arr[index-1].mainOrderItemId){
            if (item.nodeName && arr[index-1].nodeName) {
              newarr[index-1].circuitName = item.circuitName =  newarr[index-1].nodeName + '-' + item.nodeName;
            }
            delete item.comments;
            this.mergeCells.push(
                {row: index-1, col: 0, rowspan: 2, colspan: 1},
                {row: index-1, col: 15, rowspan: 2, colspan: 1}
            );
        }
        if(!item.circuitName){
          item.circuitName = item.nodeName;
        }
        item.subtotal = '￥' + (Number(item.moneyRmbMat) + Number(item.moneyRmbTest) + Number(item.moneyRmbPro));
        item.receivables = '￥' + (Number(item.moneyRmbMat) + Number(item.moneyRmbTest) + Number(item.moneyRmbPro) +
            Number(item.moneyRmbEng) + Number(item.moneyRmbDev));
        for (var key in item) {
          if (le[key]) {
            item[key] = '￥' + item[key];
          }
        }
        newarr.push(item);
      });
      
      
      return newarr;
    },
    getLabel(opt, VALUE) {
      for (var key in opt) {
        let item = opt[key];
        if (item.value == VALUE) {
          
          return item.label;
        }
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.generate-quotation-box {
  height: 84vh;
  padding-bottom: .3rem;

  .fixed {
    position: absolute;
    bottom: -.1rem;
    left: 0;
    right: 0;
    margin: 0 auto;
  }
}
</style>
